package mp

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/request"
	"duoke/utils/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"time"
)

var Statistics = new(statisticsCtl)

type statisticsCtl struct{}

func (ctl *statisticsCtl) Behavior(c *gin.Context) {
	req := request.JsonMap(c)
	action := gconv.String(req["action"])
	goods, _ := service.Request.Goods(c)
	account, _ := service.Request.Account(c)
	userR, _ := service.Request.User(c)
	user, err := service.User.Info(c, "id,nickname,avatar,name,phone")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	goodsUser, err := service.GoodsUser.GetByGoodsUserId(c, goods.Id, user.Id, "id,nickname,avatar,name,phone,staff_id")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if action == "share_app_message" {
		goods.ShareAppMessage = goods.ShareAppMessage + 1
		_, _ = orm.Db.ID(goods.Id).Update(goods)
	}
	if action == "share_timeline" {
		goods.ShareTimeline = goods.ShareTimeline + 1
		_, _ = orm.Db.ID(goods.Id).Update(goods)
	}
	behavior := new(tables.Behavior)
	behavior.Acid = account.Id
	behavior.GoodsId = goods.Id
	behavior.UserId = userR.Id
	behavior.Nickname = user.Nickname
	behavior.Avatar = user.Avatar
	behavior.Action = action
	behavior.ViewTime = gconv.Int(req["view_time"])
	behavior.ViewPercentage = gconv.Int(req["view_percentage"])
	behavior.StaffId = goodsUser.StaffId
	affected, err := orm.Db.Insert(behavior)
	if affected == 0 || err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 执行转发奖励
	if (action == "share_app_message" || action == "share_timeline") && goods.Config["forward_reward"] != "" && gconv.Float64(goods.Config["forward_reward"]) > 0 {
		remark := ""
		if action == "share_app_message" {
			remark = "转发好友奖励"
		}
		if action == "share_timeline" {
			remark = "分享朋友圈奖励"
		}
		orderNo := "for" + time.Now().Format("20060102")
		_, err = service.Reward.Send(c, 2, account.Id, goods.Id, goods.Title, userR.Id, gconv.Float64(goods.Config["forward_reward"]), orderNo, userR.Id, remark, goods.SpRewardAutoSend == 1)
		if err != nil {
			logrus.Error("转发奖励发放失败，订单号："+orderNo, err.Error())
		}
	}
	response.Success(c, "success", nil)
}
func (ctl *statisticsCtl) Course(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, total, err := service.CourseList.List(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "获取成功", gin.H{"total": total, "list": list})
}
func (ctl *statisticsCtl) CourseCount(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	if id == 0 {
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	info, err := service.CourseList.Info(c, id, "*")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	video, err := service.CourseList.CourseVideo(c, id)
	video.SubMchId = info.SubMchId
	video.Buy = info.Buy
	video.NumberOfLearners = info.NumberOfLearners
	video.Collect = info.Collect
	video.Shares = info.Shares
	video.LecturerPic = info.LecturerPic
	video.LecturerCollege = info.LecturerCollege
	video.LecturerName = info.LecturerName
	f := video.WatchTime / 60
	if f < 1 {
		video.WatchTime = 0
	} else {
		video.WatchTime = gconv.Float64(fmt.Sprintf("%.2f", f))
	}
	response.Success(c, "获取成功", video)
}
func (ctl *statisticsCtl) CourseInfo(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	validTypes := map[string]bool{"share": true, "collect": true, "buy": true, "number_of_learners": true}
	if !validTypes[req.Type] {
		response.Error(c, "类型错误【type】", nil)
		return
	}
	if req.FromId == "" {
		response.Error(c, "参数缺失【from_id】", nil)
		return
	}
	list, count, err := service.Statistics.CourseList(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"total": count, "list": list})
}
func (ctl *statisticsCtl) ShortVideoInfo(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	if id == 0 {
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	info, err := service.Shortvideo.Info(id, "*")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	f := info.WatchTime / 60
	if f < 1 {
		info.WatchTime = 0
	} else {
		info.WatchTime = float32(gconv.Float64(fmt.Sprintf("%.2f", f)))
	}
	response.Success(c, "获取成功", info)
}
func (ctl *statisticsCtl) ShortVideoCount(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	validTypes := map[string]bool{"dz": true, "zf": true, "buy": true, "watch": true, "watch_number": true,
		"watch_time": true}
	if !validTypes[req.Type] {
		response.Error(c, "类型错误【type】", nil)
		return
	}
	list, count, err := service.Statistics.ShortVideoList(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"total": count, "list": list})
}
func (ctl *statisticsCtl) CourseVideo(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	validTypes := map[string]bool{"share": true, "collect": true, "buy": true, "watch": true, "watch_number": true,
		"watch_time": true}
	if !validTypes[req.Type] {
		response.Error(c, "类型错误【type】", nil)
		return
	}
	list, count, err := service.Statistics.CourseVideo(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"total": count, "list": list})
}
